import {writable} from 'svelte/store';
import {browser} from '$app/environment';

class HandleStore {
    constructor(key,initialvalue) {
        if(!key ||(typeof key !== 'string')) {
            //抛出错误，如果遇到错误会终止运行
            throw new Error('key需要被传递，并且是String类型');
        }
        this.key = key;
        this.initialvalue = initialvalue;

        this.store = writable(this.getLocalStorage());
    }

    //得到localstorage
    getLocalStorage() {
        // 如果不在浏览器直接返回初始值
        if(!browser) return this.initialvalue;

        try{
            const item=localStorage.getItem(this.key);
            if(!item) return this.initialvalue;

            const value = JSON.parse(item);

            // 判断从localstorage得到的value是否与初始值相同
            return this.judgementdata(value) ? value : this.initialvalue;
        }
        catch (error) {
            return this.initialvalue;
        }
    }

    judgementdata(data){
        return typeof data === typeof this.initialvalue
    }


    //设置localstorage
    setLocalStorage(value){
        if(!browser) return;
        try{
            localStorage.setItem(this.key, JSON.stringify(value))
        }//存储空间有可能不足
        catch (error) {
            console.error(`store 写入${this.key}失败`);
            if(error.name==="QuotaExceededError"){
                this.errorMessage();
            }
        }
    }
    errorMessage(){
        console.error("localStorage存储空间不足");
    }

    //二次封装：直接调用 	subscribe set update方法
    subscribe = (callback,invalide)=>{
        return this.store.subscribe(callback,invalide);
    }

    set = (value)=>{
        this.setLocalStorage(value);
        this.store.set(value);
    }

    update = (callback)=>{
        this.store.update(current=>{
            const newvalue = callback(current);
            this.setLocalStorage(newvalue);
            return newvalue;
        })
    }

    // 删除localstorage
    clear = ()=>{
        if(browser){
            try {
                this.store.set(this.initialvalue);
                localStorage.removeItem(this.key);
            }
            catch (error) {
                console.error('store 删除${this.key}失败');
            }
        }
        return undefined
    }

    get value(){
        let value;
        this.store.subscribe(v => value = v);
        return value;
    }
}

export const localInfo = new HandleStore("localInfo",[]);